from django.http import HttpResponseRedirect, HttpResponse

from app01 import models
from django.shortcuts import render, redirect
from app01.utils.form import LoginForm, LoginModelForm
from app01.utils.code import check_code

def login(request):
    """登录"""
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if code.upper() != user_input_code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})
        # {'username': 'xmd', 'password': '12e929a642f6d1651efca7065d43c4d8'}
        # print(form.cleaned_data)
        # 获取登录用户名 如果错误 会返回一个FALSE
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            # 主动添加错误信息
            form.add_error("password", '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # 用户名和密码正确
        # 网站要生成一个随机身份证 写到浏览器的cookie中 再写入到session中 重点重点重点重点重点重点重点
        request.session['info'] = {'id': admin_object.id, 'name': admin_object.username}
        # 再次设置session 可以存储7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')
    return render(request, 'login.html', {'form': form})

from io import BytesIO
def img_code(request):
    """生成图片验证码"""
    # 调用函数生成图片 反馈给浏览器
    img, code_string = check_code()
    # 将验证码写入到session中 便于后期校验
    request.session['image_code'] = code_string
    # 验证码120秒超时
    request.session.set_expiry(120)
    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue(), content_type='image')

def logout(request):
    """注销"""
    request.session.clear()
    return redirect('/login/')
